<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastAPI 前端交互示例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            text-align: center;
        }

        .subtitle {
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .section {
            margin-bottom: 30px;
        }

        .section-title {
            color: #667eea;
            font-size: 18px;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input:focus {
            outline: none;
            border-color: #667eea;
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: transform 0.2s, box-shadow 0.2s;
            width: 100%;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        button:active {
            transform: translateY(0);
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .response {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 15px;
            border-radius: 6px;
            margin-top: 15px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
        }

        .response.error {
            border-left-color: #e74c3c;
            background: #ffeaea;
        }

        .response.success {
            border-left-color: #27ae60;
            background: #eafaf1;
        }

        .token-display {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 6px;
            margin-top: 10px;
            word-break: break-all;
            font-size: 12px;
            font-family: 'Courier New', monospace;
            color: #666;
        }

        .status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            margin-left: 10px;
        }

        .status.authenticated {
            background: #27ae60;
            color: white;
        }

        .status.unauthenticated {
            background: #e74c3c;
            color: white;
        }

        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>FastAPI 前端交互示例</h1>
            <p class="subtitle">演示与 FastAPI 后端 API 的交互</p>
            
            <div style="text-align: center; margin-bottom: 20px;">
                <span>认证状态：</span>
                <span id="authStatus" class="status unauthenticated">未认证</span>
            </div>
        </div>

        <!-- 注册表单 -->
        <div class="card">
            <div class="section">
                <h2 class="section-title">用户注册</h2>
                <form id="registerForm">
                    <div class="form-group">
                        <label for="regUsername">用户名</label>
                        <input type="text" id="regUsername" required>
                    </div>
                    <div class="form-group">
                        <label for="regEmail">邮箱</label>
                        <input type="email" id="regEmail" required>
                    </div>
                    <div class="form-group">
                        <label for="regPassword">密码</label>
                        <input type="password" id="regPassword" required>
                    </div>
                    <button type="submit">注册</button>
                </form>
                <div id="registerResponse" class="response" style="display: none;"></div>
            </div>
        </div>

        <!-- 登录表单 -->
        <div class="card">
            <div class="section">
                <h2 class="section-title">用户登录</h2>
                <form id="loginForm">
                    <div class="form-group">
                        <label for="loginUsername">用户名</label>
                        <input type="text" id="loginUsername" required>
                    </div>
                    <div class="form-group">
                        <label for="loginPassword">密码</label>
                        <input type="password" id="loginPassword" required>
                    </div>
                    <button type="submit">登录</button>
                </form>
                <div id="loginResponse" class="response" style="display: none;"></div>
                <div id="tokenDisplay" class="token-display" style="display: none;"></div>
            </div>
        </div>

        <!-- 用户信息 -->
        <div class="card">
            <div class="section">
                <h2 class="section-title">获取当前用户信息</h2>
                <button id="getUserBtn">获取我的信息</button>
                <div id="userResponse" class="response" style="display: none;"></div>
            </div>
        </div>

        <!-- 更新用户信息 -->
        <div class="card">
            <div class="section">
                <h2 class="section-title">更新用户信息</h2>
                <form id="updateForm">
                    <div class="form-group">
                        <label for="updateUsername">新用户名（可选）</label>
                        <input type="text" id="updateUsername">
                    </div>
                    <div class="form-group">
                        <label for="updateEmail">新邮箱（可选）</label>
                        <input type="email" id="updateEmail">
                    </div>
                    <div class="form-group">
                        <label for="updatePassword">新密码（可选）</label>
                        <input type="password" id="updatePassword">
                    </div>
                    <button type="submit">更新信息</button>
                </form>
                <div id="updateResponse" class="response" style="display: none;"></div>
            </div>
        </div>
    </div>

    <script>
        // API 基础地址
        const API_BASE = 'http://localhost:8000/api';

        // Token 存储
        let authToken = localStorage.getItem('authToken') || '';

        // 初始化
        function init() {
            updateAuthStatus();
            
            // 注册表单提交
            document.getElementById('registerForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                await handleRegister();
            });

            // 登录表单提交
            document.getElementById('loginForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                await handleLogin();
            });

            // 获取用户信息
            document.getElementById('getUserBtn').addEventListener('click', async () => {
                await getUserInfo();
            });

            // 更新用户信息
            document.getElementById('updateForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                await updateUserInfo();
            });
        }

        // 更新认证状态显示
        function updateAuthStatus() {
            const statusEl = document.getElementById('authStatus');
            if (authToken) {
                statusEl.textContent = '已认证';
                statusEl.className = 'status authenticated';
            } else {
                statusEl.textContent = '未认证';
                statusEl.className = 'status unauthenticated';
            }
        }

        // 显示响应
        function showResponse(elementId, data, isError = false) {
            const el = document.getElementById(elementId);
            el.style.display = 'block';
            el.textContent = JSON.stringify(data, null, 2);
            el.className = 'response' + (isError ? ' error' : ' success');
        }

        // 用户注册
        async function handleRegister() {
            const username = document.getElementById('regUsername').value;
            const email = document.getElementById('regEmail').value;
            const password = document.getElementById('regPassword').value;

            try {
                const response = await fetch(`${API_BASE}/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, email, password })
                });

                const data = await response.json();
                
                if (response.ok) {
                    showResponse('registerResponse', { success: true, data }, false);
                } else {
                    showResponse('registerResponse', { success: false, error: data }, true);
                }
            } catch (error) {
                showResponse('registerResponse', { success: false, error: error.message }, true);
            }
        }

        // 用户登录
        async function handleLogin() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            const formData = new FormData();
            formData.append('username', username);
            formData.append('password', password);

            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (response.ok) {
                    authToken = data.access_token;
                    localStorage.setItem('authToken', authToken);
                    updateAuthStatus();
                    
                    document.getElementById('tokenDisplay').style.display = 'block';
                    document.getElementById('tokenDisplay').textContent = `Token: ${authToken.substring(0, 50)}...`;
                    
                    showResponse('loginResponse', { success: true, message: '登录成功', token: authToken.substring(0, 20) + '...' }, false);
                } else {
                    showResponse('loginResponse', { success: false, error: data }, true);
                }
            } catch (error) {
                showResponse('loginResponse', { success: false, error: error.message }, true);
            }
        }

        // 获取用户信息
        async function getUserInfo() {
            if (!authToken) {
                showResponse('userResponse', { error: '请先登录' }, true);
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/auth/me`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });

                const data = await response.json();
                
                if (response.ok) {
                    showResponse('userResponse', { success: true, data }, false);
                } else {
                    if (response.status === 401) {
                        authToken = '';
                        localStorage.removeItem('authToken');
                        updateAuthStatus();
                    }
                    showResponse('userResponse', { success: false, error: data }, true);
                }
            } catch (error) {
                showResponse('userResponse', { success: false, error: error.message }, true);
            }
        }

        // 更新用户信息
        async function updateUserInfo() {
            if (!authToken) {
                showResponse('updateResponse', { error: '请先登录' }, true);
                return;
            }

            const updateData = {};
            const username = document.getElementById('updateUsername').value;
            const email = document.getElementById('updateEmail').value;
            const password = document.getElementById('updatePassword').value;

            if (username) updateData.username = username;
            if (email) updateData.email = email;
            if (password) updateData.password = password;

            if (Object.keys(updateData).length === 0) {
                showResponse('updateResponse', { error: '请至少提供一个更新字段' }, true);
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/users/me`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify(updateData)
                });

                const data = await response.json();
                
                if (response.ok) {
                    showResponse('updateResponse', { success: true, data }, false);
                } else {
                    showResponse('updateResponse', { success: false, error: data }, true);
                }
            } catch (error) {
                showResponse('updateResponse', { success: false, error: error.message }, true);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>


